/*******************************************************************************
 * Copyright 2011 alipay.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package com.alipay.platform.data.impl.orm;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.UriMatcher;
import android.net.Uri;
import android.util.Log;

import com.alipay.platform.core.AlipayApp;

/**
 * 读取orm-mapping文件，生成相关配置数据
 * @author sanping.li@alipay.com
 *
 */
public class OrmHelper {
	public static final String NAME_SPACE = null;
	
	private Context mContext;
	
	private String mAuthority;
	
	private String mDataBase;
	
	private int mVersion;
	
	private HashMap<Integer, String> mDataMap;
	
	private UriMatcher mUriMatcher;
	
	private ArrayList<String> mCreateCommand;
	
	private HashMap<String, String> mHashMap;
	
	public OrmHelper(Context context) {
		this.mContext = context;
		mDataMap = new HashMap<Integer, String>();
		mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		mCreateCommand = new ArrayList<String>();
		mHashMap = new HashMap<String, String>();

		AlipayApp alipayApp = (AlipayApp) context.getApplicationContext();
		try {
			parser(alipayApp.getOrmMapping());
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void parser(int id) throws XmlPullParserException, IOException, ClassNotFoundException{
		XmlPullParser parser = mContext.getResources().getXml(id);
		
		String packName = null;
		Class<?> clazz = null;
		String createCom = null;
		
		int eventType = parser.getEventType();  
		while (eventType != XmlPullParser.END_DOCUMENT) {
			if (eventType == XmlPullParser.START_TAG) {  
				String name = parser.getName();
				if(name.equals("orm-mapping")){
					packName = null;
					mAuthority =  parser.getAttributeValue(NAME_SPACE, "authority");
					mDataBase = parser.getAttributeValue(NAME_SPACE, "database");
					mVersion = Integer.parseInt(parser.getAttributeValue(NAME_SPACE, "version"));

					packName =  parser.getAttributeValue(NAME_SPACE, "package");
				}else if(name.equals("class")){
					clazz = null;
					createCom = "";
					
					String className = parser.getAttributeValue(NAME_SPACE, "name");
					String tableName = parser.getAttributeValue(NAME_SPACE, "table");
					
					createCom += ("CREATE TABLE "+tableName+" (id INTEGER PRIMARY KEY AUTOINCREMENT");
					int num = mCreateCommand.size();
					mDataMap.put(num+1, tableName);
					mUriMatcher.addURI(mAuthority, tableName, num+1);
					
					clazz = Class.forName(packName+"."+className);
					mHashMap.put(clazz.getSimpleName(), tableName);
					
					Field[] fields = clazz.getDeclaredFields();

					TableColumn column = null;
					for(Field f:fields){
						column = f.getAnnotation(TableColumn.class);
						if(column!=null){
							createCom += (", "+column.column()+" "+column.type());
						}
					}
					createCom += ")";
					
					Log.i(DataProvider.TAG, createCom);
					mCreateCommand.add(createCom);
				}
			}  
			eventType = parser.next();  
		}  
	}

	public String getDataBase() {
		return mDataBase;
	}

	public int getVersion() {
		return mVersion;
	}

	public HashMap<Integer, String> getDataMap() {
		return mDataMap;
	}

	public UriMatcher getUriMatcher() {
		return mUriMatcher;
	}

	public ArrayList<String> getCreateCommand() {
		return mCreateCommand;
	}
	
	public Uri getUri(String className){
		String table = getTableName(className);
		if(table!=null){
			return Uri.parse("content://"+mAuthority+"/"+table);
		}
		return null;
	}
	
	public String getTableName(String className){
	    return mHashMap.get(className);
	}
	
}
